<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/9/7
 * Time: 9:33
 */

namespace app\index\controller;
use app\index\model\CrmCall;
use app\index\model\CrmManage;
use app\index\model\CrmManageCall;
use app\index\model\CrmZhongPuCall;
use app\index\model\CrmZhongPuManageCall;
class FeiGe extends Base
{
    //中普云通
    public function zhong_pu_phone_call(){
        $res = (new CrmZhongPuCall())->where(['manage_id'=>$this->manage['username'],'status'=>1])->field('aNum,manage_id')->select();
        if(empty($res)) apiReturn(4000,'工号：'.$this->manage['username'].'，该业务员手机还没配置系统拨号');
        apiReturn(200,'ok',$res);
    }

    public function zhong_pu_call(){
        $aNum= input('aNum');
        $bNum= input('bNum');
        $zhong_pu_call = (new CrmZhongPuCall())->where(['manage_id'=>$this->manage['username'],'aNum'=>$aNum,'status'=>1])->field('aNum,manage_id,manage_name')->find();
        if(empty($zhong_pu_call)) apiReturn(4000,'工号：'.$this->manage['username'].'，该业务员手机还没配置系统拨号');
        $userData = json_encode($zhong_pu_call->toArray(),JSON_UNESCAPED_UNICODE);
        $subId = (new FeiGeServer())->zhong_pu_dial($zhong_pu_call['aNum'],$bNum,$userData);
        (new CrmZhongPuManageCall())->allowField('subId,manage_id')->insert(['subId'=>$subId,'manage_id'=>$this->manage['username']]);
        apiReturn(200,'ok',$subId);
    }





    //飞鸽
    public function phone_call(){
        $call['username']=$this->manage['username'];
        $call['name']=$this->manage['name'];
        $res = (new CrmCall())->where('status',1)->where('manage_id','like','%'.$call['username'].'%')->field('phone,manage_id')->select();
        if(empty($res)) apiReturn(4000,'工号：'.$call['username'].'，该业务员还没配置系统拨号或者系统拨号被管理人更改，请联系组长');
        apiReturn(200,'ok',$res);
    }
    public function call(){
        $manage_phone= input('manage_phone');
        $customer_phone= input('customer_phone');
        if(empty($manage_phone)) apiReturn(400,'请选择手机号');
        if(empty($customer_phone)) apiReturn(400,'请选择客户');
        $call['username']=$this->manage['username'];
        $call['name']=$this->manage['name'];
        $res = (new CrmCall())->where(['manage_id'=>['like',"%".$call['username']."%"],'phone'=>$manage_phone,'status'=>1])->find();
        if(empty($res)) apiReturn(4000,'工号：'.$call['username'].'，该业务员还没配置系统拨号或者系统拨号被管理人更改');
        $call['extensionNumber']=$res->extensionNumber;
        $call['calledNumber']=$customer_phone;
        $call['callingNumber']=$manage_phone;
        $call['call_id']=$res['id'];
        (new FeiGeServer())->voice_call($call);
        apiReturn(200,'呼叫成功');
    }

    public function add_call(){
        if($this->manage['group_id']!=1){
            apiReturn(4000,'无权限修改');
        }
        try{
            $data = input();
            if(empty($data['extensionNumber']) || empty($data['phone'])){
                apiReturn(4000,'请填写分机号和手机号');
            }
            if(!$this->validateMobile($data['phone'])){
                apiReturn(4000,'手机号格式错误');
            }
            if(empty($data['id'])){
                if(isset($data['manage_id'])){
                    $manage_id =  explode(',',$data['manage_id']);
                    if($manage_id){
                        foreach ($manage_id as $value){
                            if(!(new CrmManage())->where(['username'=>$value,'status'=>1])->find()){
                                apiReturn(4000,'业务员工号错误或业务员禁用：'.$value);
                            }
                        }
                    }
                }
                $data['create_time'] = $data['update_time'] = time();
                (new CrmCall())->allowField(true)->insert($data);
                apiReturn(200,'添加成功');
            }else{
                if(empty($data['manage_id'])){
                    apiReturn(4000,'业务员工号');
                }
                $manage_id =  explode(',',$data['manage_id']);
                if($manage_id){
                    foreach ($manage_id as $value){
                        if(!(new CrmManage())->where(['username'=>$value,'status'=>1])->find()){
                            apiReturn(4000,'业务员工号错误或业务员禁用：'.$value);
                        }
                    }
                }
                $data['update_time'] = time();
                (new CrmCall())->allowField('manage_id,update_time,status')->save($data,['id'=>$data['id']]);
                apiReturn(200,'修改成功');
            }
        }catch (\Exception $e){
            apiReturn(4000,'分机号或者绑定手机号已添加   ');
        }
    }

    private function validateMobile($mobile) {
        if (strlen($mobile) != 11) {
            return false;
        }
        if (!preg_match('/^1[3-9]\d{9}$/', $mobile) && !preg_match('/^0\d{2,3}\d{7,8}$/', $mobile) && !preg_match('/^(\d{3}-|\d{4}-)?\d{7,8}$/', $mobile)) {
            return false;
        }
        return true;
    }

    public function list_call(){
        $query=input();
        $query['rows'] = isset($query['rows'])?$query['rows']:10;
        $query['page'] = isset($query['page'])?$query['page']:1;
        if(!empty($query['phone'])){
            $where['phone'] = $query['phone'];
        }
        if(!empty($query['manage_id'])){
            $where['manage_id'] = ['like','%'.$query['manage_id'].'%'];
        }
        if(isset($where)){
            $call = (new CrmCall())->where($where)->limit($query['rows'])->page($query['page'])->order('manage_id asc id desc')->select();
            $count = (new CrmCall())->where($where)->count();
        }else{
            $call = (new CrmCall())->limit($query['rows'])->page($query['page'])->order('manage_id asc id desc')->select();
            $count = (new CrmCall())->count();
        }
        $CrmManageM = new CrmManage();
        foreach ($call as &$value){
            $manage_id = explode(',',$value['manage_id']);
            $value['manage']='';
            if($manage_id){
                $manage=$CrmManageM->where('username','in',$manage_id)->field('username,name,fenzu_name')->select();
                if(count($manage)>0){
                    $manage_name = $manage[0]['fenzu_name']."：";
                    foreach ($manage as $v){
                        $manage_name.=$v['name'].'->'.$v['username'].'，';
                    }
                    $value['manage']=mb_substr($manage_name, 0, -1);;
                }
            }
        }
        apiReturn(200,'ok',['count'=>$count,'list'=>$call]);
    }

    //组长分配用的接口（如果拨号管理分配好了可以不用此接口）
    public function alter_manage_call(){
        $data = input();
        if(empty($data['username']) || empty($data['id'])){
            apiReturn(4000,'请选择业务员和对应分机号');
        }
        $crm_call_m = new CrmCall();
        if($call = $crm_call_m->find($data['id'])){
            $data['update_time']=time();
            $data['manage_id']=$data['username'];
            if($crm_call_m->allowField('manage_id,update_time')->save($data,['id'=>$data['id'],'status'=>1])){
                apiReturn(200,'成功');
            }
        }
        apiReturn(4000,'失败');
    }


    public function manage_call(){
        $query=input();
        $query['rows'] = isset($query['rows'])?$query['rows']:10;
        $query['page'] = isset($query['page'])?$query['page']:1;
        if(!empty($query['starttime']) && !empty($query['endtime'])){
            $where['timestamp']=['between',[strtotime($query['starttime']),strtotime($query['endtime'])]];
        }
        if(!empty($query['username'])){
            $where['manage_id']=$query['username'];
        }
        if(!empty($query['callStatus'])){
            $where['callStatus']=$query['callStatus'];
        }
        $manage_call_m = new CrmManageCall();
        if(isset($where)){
            $list = $manage_call_m->where($where)->where("callingNumber is not null and callingNumber <> ''")->field('manage_id,id,taskId,beginTime,endTime,recoredUrl,callDuration,callStatus,calledNumber,callingNumber,customData,timestamp')->limit($query['rows'])->page($query['page'])->order('id desc')->select();
            $count = $manage_call_m->where($where)->where("callingNumber is not null and callingNumber <> ''")->count();
        }else{
            $list = $manage_call_m->where("callingNumber is not null and callingNumber <> ''")->field('manage_id,id,taskId,beginTime,endTime,recoredUrl,callDuration,callStatus,calledNumber,callingNumber,customData,timestamp')->limit($query['rows'])->page($query['page'])->order('id desc')->select();
            $count = $manage_call_m->where("callingNumber is not null and callingNumber <> ''")->count();
        }
        foreach ($list as &$value){
            $value['callDuration'] = $this->changeTimeType($value['callDuration']);
            $manage = json_decode($value['customData'],true);
            if(is_array($manage)){
                $value['manage_name']=$manage['name'];
            }else{
                $value['manage_name']='';
            }
        }
        apiReturn(200,'成功',['count'=>$count,'list'=>$list]);
    }

    private  function  changeTimeType($seconds)
    {
        if ($seconds > 3600) {
            $hours = intval($seconds / 3600);
            $time = $hours . ":" . gmstrftime('%M:%S', $seconds);
        } else {
            $time = gmstrftime('%H:%M:%S', $seconds);
        }
        return $time;
    }
}